const MongoClient = require('mongodb').MongoClient;

const url = 'mongodb://admin:jsz04005301@120.48.63.39:27017'; // MongoDB 连接 URL
const dbName = 'book'; // 数据库名称

// 将示例数据插入到 MongoDB
async function insertSampleData() {
    const client = new MongoClient(url);

    try {
        await client.connect();

        const db = client.db(dbName);
        await showMap(db);

    } catch (err) {
        console.error('数据插入失败:', err);
    } finally {
        client.close();
    }
}

insertSampleData();

async function showMap(db) {
    const page = 2; // 页码
    const pageSize = 3; // 每页显示的数量
    const sortField = 'createdAt'; // 排序字段
    const sortOrder = 1; // 排序顺序（1为升序，-1为降序）

    const author = await db.collection('user').findOne({ username: "jsz" });
    console.log(typeof author._id, "###" + author._id.toString() + "***")
    const result = await db.collection('log').aggregate([
        {
            $match: {
                userId: author._id.toString()
            }
        },
        {
            $lookup: {
                from: 'video',
                let: { videoIdStr: '$videoId' },
                pipeline: [
                    {
                        $match: {
                            $expr: {
                                $eq: ['$_id', { $toObjectId: '$$videoIdStr' }]
                            }
                        }
                    }
                ],
                as: 'video'
            }
        },
        {
            $lookup: {
                from: 'user',
                let: { userIdStr: '$userId' },
                pipeline: [
                    {
                        $match: {
                            $expr: {
                                $eq: ['$_id', { $toObjectId: '$$userIdStr' }]
                            }
                        }
                    }
                ],
                as: 'user'
            }
        },
        {
            $unwind: '$video'
        },
        {
            $unwind: '$user'
        },
        {
            $sort: {
                [sortField]: sortOrder
            }
        },
        {
            $skip: (page - 1) * pageSize
        },
        {
            $limit: pageSize
        },
        {
            $project: {
                _id: 0,
                videoId: 1,
                userId: 1,
                video: 1,
                user: 1
            }
        },

    ]).toArray();

    console.log(result);
}